import React from 'react';
import { connect } from 'react-redux';
import {
  Form,
  message,
  Icon,
  Row,
  Col,
  Spin,
  Menu,
  Dropdown
} from 'antd'
import 'styles/setting/workflow/new-workflow.scss'
import 'styles/pay-setting/payment-method/new-payment-method.scss'
import NewWorkingLeftForm from 'containers/setting/new-workflow/list-comp/left-form'
import NewWorkingRightContent from 'containers/setting/new-workflow/list-comp/right-content'
import { messages, getDefaultSetOfBook } from "share/common"
import configureStore from "stores";
import { setDefaultSetOfBook } from "actions/cache";
import 'styles/setting/workflow/new-workflow.scss'
import menuRoute from 'routes/menuRoute'
import { withRouter } from 'react-router'
//新版审批流接口
import newWorkflowService from 'containers/setting/new-workflow/new-workflow.service'
import noDataImg from 'images/no-data.png';
class NewWorkingList extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      nowNode: {},
      setOfBooksId: props.company.setOfBooksId,
      setOfBooksName: props.company.setOfBooksName,
      approveRuleModalVisible: false,
      loading: false,
      setOfBooks: [],
      formListFromType: null,
      isOpened: false,
      formType: null,
      workflowDetail: menuRoute.getRouteItem('workflow-setting', 'key'), //审批流设置
    };
  }

  componentDidMount() {
    this.props.router.setRouteLeaveHook(
      this.props.route,
      this.routerWillLeave
    )
  }

  routerWillLeave = (nextLocation) => {
    if (this.state.isOpened) {
      return messages('setting.key1950')/*尚未保存，是否确认退出？*/;
    }
  };

  componentWillMount() {
    const { tenantMode } = this.props;
    this.setState({
      loading: true,
    })
    if (tenantMode) {
      getDefaultSetOfBook().then(resp => {
        if (resp.data) {
          this.setState({
            setOfBooks: resp.data,
            setOfBooksId: resp.data.defaultSetOfBooksId,
            setOfBooksName: resp.data.defaultSetOfBooksName
          }, () => {
            let params = {
              booksID: resp.data.defaultSetOfBooksId,
              roleType: 'TENANT'
            };
            this.getCustomFormList(params);
            // this.getList();
          });
        }
      }).catch(error => {
        message.error(messages('common.error'));
      });
    } else {
      let params = {
        fromType: '1',
      };
      this.getCustomFormList(params);
    }
  }

  //获取表单列表
  getCustomFormList = (params) => {
    newWorkflowService.getCustomFormList(params)
      .then(res => {
        let list = {
          '1001': [],
          '1002': [],
          '3001': [],
          '4001': [],
        };
        this.setState({
          loading: false,
          formListFromType: JSON.stringify(res.data) === '{}' ? list : res.data
        })
      })
      .catch(err => {
          this.setState({
            loading: false
          });
          if (err.response && err.response.data) {
            message.error(err.response.data.message);
          } else {
            message.error(messages('common.error'));
          }
        }
      )
  }

  componentWillReceiveProps(nextProps) {
    this.setState({
      nowNode: nextProps.params.nowNode,
      formFieldList: nextProps.params.formFieldList,
      ruleRoutes: nextProps.params.ruleRoutes,
      formInfo: nextProps.params.formInfo,
    })
  }

  onCancel = () => {
    this.setState({
      // newSheet: this.state.saveParam,
    }, function() {
      this.props.form.resetFields();
      this.props.close();
    })
  };


  handleSelect = (formOID, formType) => {
    this.setState({ formOID, formType })
  };

  handleOpen = (res) => {
    this.setState({ isOpened: res });
  };

  handleDetail = (record, formOID) => {
    let { setOfBooksName, setOfBooksId }=this.state;
    let url = this.state.workflowDetail.url.replace(':formOID', formOID);
    url += this.props.tenantMode ? `?setOfBooksId=${setOfBooksId}&setOfBooksName=${setOfBooksName}&version=${record.version}` : `?version=${record.version}`;
    this.context.router.push(url);
  };

  getCurrentSetOfBooksName = (id) => {
    let currentSetOfBooksName = '';
    this.state.setOfBooks.map((item) => {
      if (item.id === id) {
        currentSetOfBooksName = item.setOfBooksName;
      }
    });
    return currentSetOfBooksName;
  };

  handleSearchList = (e) => {
    if (e.key !== this.state.setOfBooksId) {
      this.setState({
        loading: true,
        setOfBooksId: e.key,
        setOfBooksName: this.getCurrentSetOfBooksName(e.key)
      });
      configureStore.store.dispatch(setDefaultSetOfBook({
        setOfBooksId: e.key,
        setOfBooksName: this.getCurrentSetOfBooksName(e.key)
      }));
      let params = {
        booksID: e.key,
        roleType: 'TENANT'
      };
      this.getCustomFormList(params);
      // this.getList()
    }
  };

  render() {
    let { formOID, formType, setOfBooksName, setOfBooksId, formListFromType, loading, setOfBooks } = this.state;
    const { tenantMode, language } = this.props;
    const menuSetOfBooks = (
      <Menu onClick={this.handleSearchList}>
        {this.state.setOfBooks.map(item => <Menu.Item key={item.id}>{item.setOfBooksName}</Menu.Item>)}
      </Menu>
    );
    return (
      <Row className="workflow-list">
        <Spin spinning={loading}>
          <Col span={5}>
            {tenantMode && (
              <div style={{ marginBottom: 20 }}>
                <span>{messages('setting.key503'/*帐套*/)}：</span>
                <Dropdown overlay={menuSetOfBooks}>
                  <span className='default-color-font'>{setOfBooksName} <Icon type="down"/></span>
                </Dropdown>
              </div>
            )}
            {formListFromType &&
            <NewWorkingLeftForm formListFromType={formListFromType}
                                setOfBooksId={setOfBooksId}
                                onSelectForm={this.handleSelect}/>
            }
          </Col>
          <Col span={19}>
            {formOID && <NewWorkingRightContent
              onSelectOldDetail={(record) => this.handleDetail(record, formOID)}
              formOID={formOID}
              formType={formType}
              onOpen={this.handleOpen}
              setOfBooksId={setOfBooksId}
            />
            }
            {
              !formOID && <div
                className="no-data">
                <div className="img-wrap">
                  <img src={noDataImg}/>
                </div>
                <div className="mess-wrap">{messages('setting.key1307'/*暂无数据*/)}</div>
              </div>
            }
          </Col>
        </Spin>
      </Row>
    )
  }
}

NewWorkingList.PropTypes = {
  onOpenAdditionModal: React.PropTypes.string.func,
};

NewWorkingList.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    company: state.login.company,
    user: state.login.user,
    language: state.main.language,
    tenantMode: state.main.tenantMode,
  }
}

const WrappedNewWorkingList = Form.create()(NewWorkingList);

export default withRouter(connect(mapStateToProps)(WrappedNewWorkingList));
